package com.feihong.txgw.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.widget.Toast;

import com.feihong.txgw.R;
import com.feihong.txgw.http.HttpTools;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.message.RefreshMsgIconMessage;
import com.feihong.txgw.ui.activity.base.BaseActivity;
import com.feihong.txgw.ui.fragment.base.BaseFragment;
import com.feihong.txgw.ui.fragment.home.DiscoverFragment;
import com.feihong.txgw.ui.fragment.home.HomeFragment;
import com.feihong.txgw.ui.fragment.home.ShopCarFragment;
import com.feihong.txgw.ui.fragment.home.ShoppingCartFragment;
import com.feihong.txgw.ui.fragment.home.UserFragment;
import com.feihong.txgw.utils.BottomNavigationViewHelper;
import com.feihong.txgw.utils.ScreenUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import ezy.boost.update.UpdateManager;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.PermissionRequest;


/**
 * 通讯顾问
 * 首页
 */
public class HomeActivity extends BaseActivity {

    @BindView(R.id.home_tl) BottomNavigationView mNavigat;
    private BaseFragment[] fragments = new BaseFragment[4];
    private BaseFragment currentFragment = null;

    /**
     * 测试push
     */
    @Override
    public void setTheme() {
        ScreenUtil.setStatusBarDarkFont(this,false);
    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_home;
    }
    @Override
    public void initView(Bundle savedInstanceState) {

        EventBus.getDefault().register(this);
        fragments = new BaseFragment[4];
        HomeFragment homeFragment = findFragment(HomeFragment.class);
        if (homeFragment == null) {

            homeFragment = HomeFragment.newInstance(HomeFragment.class.getName());
            DiscoverFragment discoverFragment = DiscoverFragment.newInstance(DiscoverFragment.class.getName());
            ShopCarFragment shoppingCartFragment = ShopCarFragment.newInstance(ShoppingCartFragment.class.getName());
            UserFragment userFragment = UserFragment.newInstance(UserFragment.class.getName());
            fragments[0] = homeFragment;
            fragments[1] = discoverFragment;
            fragments[2] = shoppingCartFragment;
            fragments[3] = userFragment;
            loadMultipleRootFragment(R.id.home_tab, 0, fragments);
        } else {
            DiscoverFragment discoverFragment = findFragment(DiscoverFragment.class);
            if (discoverFragment == null) {
                discoverFragment = DiscoverFragment.newInstance(DiscoverFragment.class.getName());
            }
            ShopCarFragment shoppingCartFragment = findFragment(ShopCarFragment.class);
            if (shoppingCartFragment == null) {
                shoppingCartFragment = ShopCarFragment.newInstance(ShopCarFragment.class.getName());
            }
            UserFragment userFragment = findFragment(UserFragment.class);
            if (userFragment == null) {
                userFragment = UserFragment.newInstance(UserFragment.class.getName());
            }
            fragments[0] = homeFragment;
            fragments[1] = discoverFragment;
            fragments[2] = shoppingCartFragment;
            fragments[3] = userFragment;
        }
        currentFragment = fragments[0];
        mNavigat.setSelectedItemId(R.id.action_home);
        checkUpdate();
    }

    private void checkUpdate() {
        // 设置默认更新接口地址与渠道
        UpdateManager.setUrl(HttpTools.UPDATE_APP, "Android");
        //设置不是WIFI也可以检测更新版本 ，默认的是只WIFI情况下检测新版本
        UpdateManager.setWifiOnly(false);
        // 进入应用时查询更新
        UpdateManager.check(this);
    }

    @Override
    public void bindData() {
        BottomNavigationViewHelper.disableShiftMode(mNavigat);
        mNavigat.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()){
                    case R.id.action_home:
                        showHideFragment(fragments[0],currentFragment);
                        currentFragment = fragments[0];
                        break;
                    case R.id.action_disconver:
                        showHideFragment(fragments[1],currentFragment);
                        currentFragment = fragments[1];
                        break;
                    case R.id.action_shopcar:
                        showHideFragment(fragments[2],currentFragment);
                        currentFragment = fragments[2];
                        break;
                    case R.id.action_mine:
                        showHideFragment(fragments[3],currentFragment);
                        currentFragment = fragments[3];
                        break;
                    default:break;
                }
                return true;
            }
        });
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    boolean isExit;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mNavigat.getSelectedItemId() != R.id.action_home) {
                mNavigat.setSelectedItemId(R.id.action_home);
                return true;
            } else {
                exit();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if (!isExit) {
            isExit = true;
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
            mHandler.sendEmptyMessageDelayed(0, 2000);
        } else {
            //mRequestMap.remove(HomeActivity.class.getName());
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            System.exit(0);
        }
    }

    Handler mHandler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }

    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        currentFragment.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
        if(mHandler != null){
            mHandler.removeCallbacksAndMessages(null);
        }
    }


    private void showRationaleDialog(String message, final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage(message)
                .show();
    }

    public boolean isHaveNewMsg = false;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshHomeMsgIcon(RefreshMsgIconMessage refreshMsgIconMessage) {
        if (refreshMsgIconMessage.getData().isHaveNewMsg()) {
            isHaveNewMsg =  true;
        } else {
            isHaveNewMsg =  false;
        }
    }
    @OnNeverAskAgain(Manifest.permission.ACCESS_COARSE_LOCATION)
    void onNeverAskAgain() {

    }

    //
//    private AtomicBoolean isShowDialog;
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void forceExit(ForceExitLogin forceExitLogin){
//        if(isShowDialog.compareAndSet(true,false)){
//            Log.i(TAG, "forceExit: 强制退出");
//            UserLoginInfo.userExitLogin();
//            // 退出登录时  将默认收货地址的缓存清空
//            PreferenceTools.putString(MyDeliveryAdrActivity.DEFAULT_ADR_KEY, "");
//            PreferenceTools.putString("ll_info_result","");
//            //应该把我的->用户名称 还原
//            try {
//                CacheDataManger.getTotalCacheSize(HomeActivity.this).startsWith("0");
//            }catch (Exception e){
//
//            }
//            LoginMessage loginMessage = new LoginMessage();
//            loginMessage.setAction(LoginMessage.ACTION_EXIT);
//            GreenDaoOperateHelper.delAll();
//            EventBus.getDefault().post(loginMessage);
//            UserLoginInfo.updateUserToken("");
//            App.getApp().lastUpdateToken = 0;
//            showErrorDialogFromBase(null,"您的身份信息已失效，请重新登录",new DialogInterface.OnDismissListener() {
//                @Override
//                public void onDismiss(DialogInterface dialog) {
////                    Intent intent = new Intent("com.feihong.txgw.ui.activity.user.LoginActivity");
////                    startActivity(intent);
//                    isShowDialog.compareAndSet(false,true);
//                }
//            });
//        }
//    }
}
